/**
 * Copyright (c) 2011, www.quartzsource.org
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.quartzsource.core
import scala.util.matching.Regex
import java.net.URL
import java.io.File

case class QURL(
  scheme: QURL.Scheme,
  user: Option[String],
  pass: Option[String],
  host: Option[String],
  port: Option[Int],
  path: String, // may be empty
  query: Option[String],
  revision: Option[String],
  source: String) {
  override def toString = {
    source
  }
}
object QURL {
  sealed trait Scheme
  case object File extends Scheme
  case object Bundle extends Scheme
  case object Http extends Scheme
  case object Https extends Scheme
  case object Ssh extends Scheme
  object Scheme {
    def apply(s: String): Scheme = s match {
      case "file" => File
      case "bundle" => File
      case "http" => Http
      case "https" => Https
      case "ssh" => Ssh
      case error => throw new QuartzException("Unexpected scheme: " + error)
    }
  }
  def apply(path: String, parseQuery: Boolean = true, parseFragment: Boolean = true): QURL = {
    //TODO expand '~' to the value of HOME (util.expandpath)
    val HttpPattern = new Regex("""(\w+)://(\w+@)(\S+?)/(.*)""")
    path match {
      case HttpPattern(scheme, user, host, query) =>
        new QURL(Scheme(scheme), Some(user.dropRight(1)), None, Some(host), None, "/" + query, None, None, path)
      case local =>
        new QURL(QURL.File, None, None, None, None, local, None, None, path)
    }
  }

  def apply(path: URL): QURL = {
    new QURL(QURL.Http, Some(path.getUserInfo()), None, Some(path.getHost()), None, path.getPath(), None, None, path.toString())
  }

  def apply(path: File): QURL = {
    new QURL(QURL.File, None, None, None, None, path.toURI.toString, None, None, path.toString())
  }
}

